package com.minivision.sdktestdemo.ui;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.minivision.sdktestdemo.R;
import com.minivision.sdktestdemo.bean.MusicBean;
import com.minivision.sdktestdemo.event.DataModificationEvent;
import com.minivision.sdktestdemo.model.MusicProvider;
import com.minivision.sdktestdemo.model.Provider;
import com.minivision.sdktestdemo.theme.utils.ThemeUtils;
import com.minivision.sdktestdemo.ui.view.PopClickItemFactory;
import com.minivision.sdktestdemo.utils.AlertDialogUtils;
import com.minivision.sdktestdemo.utils.LoadingWindowUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link MusicEditFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link MusicEditFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MusicEditFragment extends Fragment implements MusicEditRecyclerAdapter.OnItemCheckedListener, Toolbar.OnMenuItemClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public MusicEditFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MusicEditFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MusicEditFragment newInstance(String param1, String param2) {
        MusicEditFragment fragment = new MusicEditFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        setHasOptionsMenu(true);
    }

    @Bind(R.id.music_list)
    RecyclerView mRecylerView;

    MusicEditRecyclerAdapter mAdapter;

    private MusicNavFragment.ToolBarHelper mHelper;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_music_edit, container, false);
        ThemeUtils.initTheme(view);
        ButterKnife.bind(this, view);
        initData();
        initView();
        return view;
    }

    private void initData() {
        if (mList == null) {
            throw new IllegalStateException("list不能为空");
        }
        mAdapter = new MusicEditRecyclerAdapter(mList);
        mAdapter.setOnItemCheckedListener(this);
        mExecutor = Executors.newSingleThreadExecutor();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        final AppCompatActivity appCompatActivity = (AppCompatActivity) getActivity();
        menu.setGroupVisible(R.id.system_group, false);
        mHelper.getToolbar().setLogo(null);
        mHelper.getToolbar().setTitle("已选择0项");
        mHelper.getToolbar().setNavigationIcon(R.drawable.ic_action_arrow_left);
        mHelper.getToolbar().setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                appCompatActivity.onBackPressed();
            }
        });
        mHelper.getToolbar().setOnMenuItemClickListener(this);
        inflater.inflate(R.menu.edit_top_menu, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    private void initView() {
        mRecylerView.setHasFixedSize(true);
        mRecylerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecylerView.setAdapter(mAdapter);
    }

    private ExecutorService mExecutor;

    private int mRemoveFlag;

    @OnClick(R.id.btn_delete)
    public void onDelete() {
        AlertDialogUtils.getDeleteDialog(getActivity(), new PopClickItemFactory.OnDeleteListener() {
            @Override
            public void onDelete(final boolean isDeletedFlag) {
                LoadingWindowUtils.showProgressBack(getActivity(), true);
                Observable.just(isDeletedFlag)
                        .map(new Func1<Boolean, DataModificationEvent>() {
                            @Override
                            public DataModificationEvent call(Boolean aBoolean) {
                                List<MusicBean> beans = mAdapter.removeAllChecked();
                                DataModificationEvent modificationEvent = new DataModificationEvent(new ArrayList<MusicBean>(), DataModificationEvent.ACTION_DELETE);
                                modificationEvent.mAction = DataModificationEvent.ACTION_DELETE;
                                MusicProvider provider = MusicProvider.getInstance(getActivity());
                                mRemoveFlag = provider.remove(beans, isDeletedFlag);
                                Provider.adjustGroup(getActivity(), beans);
                                return modificationEvent;
                            }
                        })
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Action1<DataModificationEvent>() {
                            @Override
                            public void call(DataModificationEvent event) {
                                LoadingWindowUtils.showProgressBack(getActivity(), false);
                                mAdapter.notifyDataSetChanged();
                                mHelper.getToolbar().setTitle("已选择0项");
                                if (mRemoveFlag == -1) {
                                    Toast.makeText(getContext(), "删除失败", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(getContext(), "删除成功", Toast.LENGTH_SHORT).show();
                                }
                                EventBus.getDefault().post(event);
                            }
                        });

//                mExecutor.execute(new Runnable() {
//                    @Override
//                    public void run() {
//                        List<MusicBean> beans = mAdapter.removeAllChecked();
//                        DataModificationEvent modificationEvent = new DataModificationEvent(new ArrayList<MusicBean>(), DataModificationEvent.ACTION_DELETE);
//                        modificationEvent.mAction = DataModificationEvent.ACTION_DELETE;
//                        MusicProvider provider = MusicProvider.getInstance(getActivity());
//                        final int res = provider.remove(beans, isDeletedFlag);
//                        Provider.adjustGroup(getActivity(), beans);
//                        getActivity().runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                LoadingWindowUtils.showProgressBack(getActivity(), false);
//                                mAdapter.notifyDataSetChanged();
//                                mHelper.getToolbar().setTitle("已选择0项");
//                                if (res == -1) {
//                                    Toast.makeText(getContext(), "删除失败", Toast.LENGTH_SHORT).show();
//                                } else {
//                                    Toast.makeText(getContext(), "删除成功", Toast.LENGTH_SHORT).show();
//                                }
//                            }
//                        });
//                        EventBus.getDefault().post(modificationEvent);
//                    }
//                });
            }
        }, getString(R.string.dialog_delete)).show();
    }

    private List<MusicBean> mList;

    public void setListBean(List<MusicBean> list) {
        mList = list;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mHelper = (MusicNavFragment.ToolBarHelper) context;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
        mHelper = null;
    }

    @Override
    public void onItemChecked(int position) {
        int count = mAdapter.getCheckedCount();
        adjustMenuItem(mHelper.getToolbar().getMenu().findItem(R.id.select_all), count);
        mHelper.getToolbar().setTitle("已选择" + count + "项");
    }

    public void adjustMenuItem(MenuItem item, int count) {
        if (count != mList.size()) {
            item.setTitle(getString(R.string.select_all));
        } else {
            item.setTitle(getString(R.string.dis_select_all));
        }
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        if (item.getItemId() == R.id.select_all) {
            if (item.getTitle().equals(getString(R.string.select_all))) {
                mAdapter.selectAllChecked();
                item.setTitle(getString(R.string.dis_select_all));
            } else {
                mAdapter.cancelAllChecked();
                item.setTitle(getString(R.string.select_all));
            }
            mAdapter.notifyDataSetChanged();
            mHelper.getToolbar().setTitle("已选择" + mAdapter.getCheckedCount() + "项");
            return true;
        }
        return false;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
